<template>
  <div class="purchase-information">
    <div class="common-title">
      <h1>土壤检测信息</h1>
      <p>SOIL TESTTING INFORMATION</p>
    </div>
    <van-cell-group class="mg-bot-10">
      <van-field
        v-model="samplingTime"
        label="取样时间"
        placeholder="请选择"
        :readonly="true"
        input-align="right"
        right-icon="arrow"
        @focus="timePick"
        class="required"
      />
      <van-field
        v-model="areaInfo"
        label="省市县"
        placeholder="请选择"
        :readonly="true"
        input-align="right"
        right-icon="arrow"
        @focus="addressPick"
        class="required"
      />
      <van-field class="required" v-model="address" label="详细地址" placeholder="请填写" />
      <!-- <van-field
        v-model="soilName"
        label="土壤类型"
        placeholder="请选择"
        :readonly="true"
        input-align="right"
        right-icon="arrow"
        @focus="soilPick"
        class="required"
      />
      <van-field
        v-model="textureName"
        label="土壤质地"
        placeholder="请选择"
        :readonly="true"
        input-align="right"
        right-icon="arrow"
        @focus="texturePick"
        class="required"
      />-->
      <van-field class="required" v-model="plantArea" label="种植面积" placeholder="亩" />
    </van-cell-group>
    <div class="common-title">
      <h1>测土人信息</h1>
      <p>GEODESIC INFORMATION</p>
    </div>
    <van-cell-group class="mg-bot-10">
      <van-field v-model="name" label="姓名" placeholder="请填写" class="required" />
      <van-field v-model="phone" label="电话" placeholder="请填写" class="required" />
      <!-- <van-field v-model="purpose" label="测土用途" placeholder="请填写" class="required" /> -->
    </van-cell-group>
    <div class="common-title">
      <h1>土壤作物信息</h1>
      <p>SOIL CROP INFORMATION</p>
    </div>
    <van-cell-group class="mg-bot-10">
      <van-field v-model="previousCrop" label="前茬作物" placeholder="请填写" />
      <!-- <van-field v-model="output" label="产量水平" placeholder="请输入多少公斤/亩" /> -->
      <van-field v-model="seasonCrop" label="当季作物" placeholder="请填写" />
      <!-- <van-field v-model="targetOutput" label="目标产量" placeholder="请输入多少公斤/亩" /> -->
    </van-cell-group>
    <div class="common-title">
      <h1>发票信息</h1>
      <p>INVOICE INGFORMATION</p>
    </div>
    <van-cell-group class="mg-bot-10">
      <van-field
        v-model="invoiceStatus"
        label="开具发票"
        :readonly="true"
        input-align="right"
        right-icon="arrow"
        @focus="goInvoice"
      />
    </van-cell-group>
    <div class="common-title">
      <h1>支付方式</h1>
      <p>PAYMENT METHOD</p>
    </div>
    <div class="purchase-information-bottom">
      <div class="weixin-img">
        <img src="../../assets/images/weixin-check.png" alt class="weixin-img1" />
        <img src="../../assets/images/weixin.png" alt class="weixin-img2" />
        <span>微信支付</span>
      </div>
      <div class="contract">
        <van-checkbox v-model="contractChecked" checked-color="#07c160">已经查阅并同意</van-checkbox>
        <span @click="goContract()">《种植密码免责协议》</span>
      </div>
      <div
        class="purchase-information-btn"
        :class="contractChecked?'':'no-submit'"
        @click="goOrderPay()"
      >立即支付</div>
    </div>
    <van-popup v-model="samplingTimeShow" position="bottom">
      <van-datetime-picker
        v-model="currentDate"
        type="date"
        title="选择年月日"
        :min-date="minDate"
        :max-date="maxDate"
        :formatter="formatter"
        @confirm="onConfirmTime"
        @cancel="onCancel"
        @change="onChangeTime"
      />
    </van-popup>
    <van-popup v-model="soilShow" position="bottom">
      <van-picker
        title="土壤类型列表"
        show-toolbar
        value-key="name"
        :columns="soilList"
        @confirm="onConfirmSoil"
        @cancel="onCancel"
        @change="onChangeSoil"
      />
    </van-popup>
    <van-popup v-model="textureShow" position="bottom">
      <van-picker
        title="土壤地质列表"
        show-toolbar
        value-key="name"
        :columns="textureList"
        @confirm="onConfirmTexture"
        @cancel="onCancel"
        @change="onChangeTexture"
      />
    </van-popup>
    <van-popup v-model="addressShow" position="bottom">
      <van-picker
        :columns="addressList"
        show-toolbar
        value-key="area_name"
        @confirm="onConfirmAddress"
        @cancel="addressShow = false"
        @change="onChangeAddress"
      />
    </van-popup>
  </div>
</template>
<script>
import {
  orderPay,
  orderPayZero,
  areaList,
  soilType,
  textureType,
} from "@/api/common";
export default {
  data() {
    return {
      key: "",
      areaId: "",
      cityId: "",
      samplingTime: "",
      areaInfo: "",
      address: "",
      soilName: "",
      soilId: "",
      textureName: "",
      textureId: "",
      previousCrop: "",
      output: "",
      seasonCrop: "",
      targetOutput: "",
      name: "",
      phone: "",
      purpose: "",
      plantArea: "",
      invoiceId: "",
      invoiceStatus: "不开票",
      proofPath: "",
      sampleNumber: "",
      soilList: [],
      soilShow: false,
      textureList: [],
      textureShow: false,
      samplingTimeShow: false,
      minDate: new Date(2020, 0, 1),
      maxDate: new Date(2025, 10, 1),
      currentDate: new Date(),
      addressColumn1: [],
      addressColumn2: [],
      addressColumn3: [],
      areaId: "",
      cityId: "",
      addressId: "",
      addressList: [],
      areaInfo: "",
      addressShow: false,
      canSubmit: true,
      paymentAmountType: 1,
      contractChecked: true,
      latitude: "",
      longitude: "",
    };
  },
  mounted() {
    this.init();
    this.getSoilType();
    this.getTextureType();
    this.getAddressList();
  },
  methods: {
    init() {
      this.key = localStorage.getItem("userKey");
      this.sampleNumber = this.$route.query.sample_number;
      this.proofPath = this.$route.query.proof_path;
      this.paymentAmountType = this.$route.query.payment_amount_type;
      let testingInfo = JSON.parse(localStorage.getItem("testingInfo"));

      if (testingInfo) {
        this.key = testingInfo.key;
        this.areaId = testingInfo.area_id;
        this.cityId = testingInfo.city_id;
        this.samplingTime = testingInfo.sampling_time;
        this.areaInfo = testingInfo.area_info;
        this.address = testingInfo.address;
        this.soilId = testingInfo.soil_id;
        this.textureId = testingInfo.texture_id;
        this.plantArea = testingInfo.plant_area;
        this.soilName = testingInfo.soil_name;
        this.textureName = testingInfo.texture_name;
        this.previousCrop = testingInfo.previous_crop;
        this.output = testingInfo.output;
        this.seasonCrop = testingInfo.season_crop;
        this.targetOutput = testingInfo.target_output;
        this.phone = testingInfo.phone;
        this.name = testingInfo.name;
        this.purpose = testingInfo.purpose;
        this.invoiceId = testingInfo.invoice_id;
        this.proofPath = testingInfo.proof_path;
        this.sampleNumber = testingInfo.sample_number;
        this.latitude = testingInfo.latitude;
        this.longitude = testingInfo.longitude;
        this.paymentAmountType = testingInfo.payment_amount_type;
      }
      this.invoiceId = localStorage.getItem("invoiceId");
      if (this.invoiceId) {
        this.invoiceStatus = "开票";
      }
      this.samplingTime = this.dateFilter(new Date());
    },
    dateFilter(time) {
      var y = time.getFullYear();
      var m = time.getMonth() + 1;
      var d = time.getDate();
      return y + "-" + this.add0(m) + "-" + this.add0(d);
    },
    add0(m) {
      return m < 10 ? "0" + m : m;
    },
    onCancel() {
      this.soilShow = false;
      this.textureShow = false;
      this.samplingTimeShow = false;
    },
    formatter(type, value) {
      if (type === "year") {
        return `${value}年`;
      } else if (type === "month") {
        return `${value}月`;
      } else if (type === "day") {
        return `${value}日`;
      }
      return value;
    },
    timePick() {
      this.samplingTimeShow = true;
    },
    onChangeTime(e) {
      let timeArr = e.getValues();
      this.samplingTime =
        timeArr[0].slice(0, 4) +
        "-" +
        timeArr[1].slice(0, 2) +
        "-" +
        timeArr[2].slice(0, 2);
    },
    onConfirmTime(e) {
      this.samplingTimeShow = false;
    },
    getSoilType() {
      soilType()
        .then((res) => {
          let code = res.data.code;
          if (code == 200) {
            this.soilList = res.data.datas.data;
          }
        })
        .catch((error) => {});
    },
    soilPick() {
      this.soilShow = true;
    },
    onChangeSoil(value, index) {},
    onConfirmSoil(value, index) {
      this.soilName = value.name;
      this.soilId = value.id;
      this.soilShow = false;
    },
    getTextureType() {
      textureType()
        .then((res) => {
          let code = res.data.code;
          //   console.log("地质类型列表", res.data);
          if (code == 200) {
            this.textureList = res.data.datas.data;
          }
        })
        .catch((error) => {});
    },
    texturePick() {
      this.textureShow = true;
    },
    onChangeTexture(value, index) {},
    onConfirmTexture(value, index) {
      this.textureName = value.name;
      this.textureId = value.id;
      this.textureShow = false;
    },
    goOrderPay() {
      let reg = /^1[3456789]\d{9}$/;
      if (!this.contractChecked) {
        this.$toast("请查阅并同意协议");
        return;
      } else if (!this.samplingTime) {
        this.$toast("请填写取样时间");
        return;
      } else if (!this.areaInfo) {
        this.$toast("请选择地址");
        return;
      } else if (!this.address) {
        this.$toast("请填写详细地址");
        return;
      } else if (!this.plantArea) {
        this.$toast("请填写种植面积");
        return;
      } else if (!this.name) {
        this.$toast("请填写姓名");
        return;
      } else if (!this.phone) {
        this.$toast("请填写电话");
        return;
      } else if (!reg.test(this.phone)) {
        this.$toast("请输入正确的手机号");
        return;
      } else if (this.canSubmit) {
        this.canSubmit = false;
        this.getLatAndLng();
      } else {
        this.$toast("请勿重复提交");
        return;
      }
    },
    getLatAndLng() {
      let detailAddress = this.areaInfo + "/" + this.address;
      this.$jsonp("http://api.map.baidu.com/geocoding/v3/", {
        address: detailAddress,
        output: "json",
        ak: "OYpdW6R7KDPQ3IAp1DurINAGOBwi05Mt",
      })
        .then((json) => {
          this.latitude = json.result.location.lat;
          this.longitude = json.result.location.lng;
          this.checkPayStyle();
        })
        .catch((err) => {
          console.log(err);
        });
    },
    checkPayStyle() {
      let data = {
        key: this.key,
        area_id: this.areaId,
        city_id: this.cityId,
        sampling_time: this.samplingTime,
        area_info: this.areaInfo,
        address: this.address,
        soil_id: this.soilId,
        texture_id: this.textureId,
        plant_area: this.plantArea,
        previous_crop: this.previousCrop,
        output: this.output,
        season_crop: this.seasonCrop,
        target_output: this.targetOutput,
        phone: this.phone,
        name: this.name,
        purpose: this.purpose,
        invoice_id: this.invoiceId,
        proof_path: this.proofPath,
        sample_number: this.sampleNumber,
        latitude: this.latitude,
        longitude: this.longitude,
        payment_amount_type: this.paymentAmountType
      };
      localStorage.setItem("invoiceId", "");
      if (this.paymentAmountType == 3 || this.paymentAmountType == 4) {
        this.zeroOrderPay(data);
      } else {
        this.pubilcOrderPay(data);
      }
    },
    zeroOrderPay(data) {
      orderPayZero(data)
        .then((res) => {
          if (res.data.code == 200) {
            // 支付成功
            this.$router.push({
              name: "pay-notify",
              query: {
                pay: 1,
              },
            });
          } else {
            //支付失败
            this.$router.push({
              name: "pay-notify",
              query: {
                pay: 0,
              },
            });
          }
        })
        .catch((error) => {});
    },
    pubilcOrderPay(data) {
      orderPay(data)
        .then((res) => {
          this.canSubmit = true;
          let code = res.data.code;
          if (code == 200) {
            localStorage.removeItem("testingInfo");
            let config = res.data.datas.mp_data;
            // 判断一下 config 如果没有数据的情况
            if (typeof WeixinJSBridge == "undefined") {
              if (document.addEventListener) {
                document.addEventListener(
                  "WeixinJSBridgeReady",
                  this.onBridgeReady(config),
                  false
                );
              } else if (document.attachEvent) {
                document.attachEvent(
                  "WeixinJSBridgeReady",
                  this.onBridgeReady(config)
                );
                document.attachEvent(
                  "onWeixinJSBridgeReady",
                  this.onBridgeReady(config)
                );
              }
            } else {
              this.onBridgeReady(config);
            }
          } else {
            this.$toast(res.data.message);
          }
        })
        .catch((error) => {});
    },
    makeData() {
      let columns = [
        {
          values: this.addressColumn1,
          defaultIndex: 0,
        },
        {
          values: [],
          defaultIndex: 0,
        },
        {
          values: [],
          defaultIndex: 0,
        },
      ];
      this.addressList = columns;
    },
    addressPick() {
      this.addressShow = true;
    },
    onChangeAddress(picker, value, index) {
      if (index == 0) {
        let i = value[0]["area_id"];
        this.addressId = i;
        this.getAddressList(1);
        setTimeout(() => {
          let item = this.addressColumn2.length > 0 ? this.addressColumn2 : [];
          if (item && item[0]["area_name"] != "请选择") {
            item.unshift({
              area_id: 0,
              area_name: "请选择",
            });
          }
          picker.setColumnValues(1, item);
        }, 500);
        this.addressColumn3 = [];
        picker.setColumnValues(2, this.addressColumn3);
      } else if (index == 1) {
        let i = value[1]["area_id"];
        this.cityId = i;
        this.addressId = i;
        this.getAddressList(2);
        setTimeout(() => {
          let item = this.addressColumn3.length > 0 ? this.addressColumn3 : [];
          if (item && item[0]["area_name"] != "请选择") {
            item.unshift({
              area_id: 0,
              area_name: "请选择",
            });
          }
          picker.setColumnValues(2, item);
        }, 500);
      } else {
        let i = value[2]["area_id"];
        this.areaId = i;
        this.addressId = i;
      }
    },
    onConfirmAddress(value, index) {
      if (index.indexOf(0) > -1) {
        this.$toast("请选择");
      } else {
        let content =
          value[0]["area_name"] +
          " / " +
          value[1]["area_name"] +
          " / " +
          value[2]["area_name"];
        this.areaInfo = content;
        this.addressShow = false;
      }
    },
    getAddressList(type) {
      if (type == 1) {
        this.getCity();
      } else if (type == 2) {
        this.getArea();
      } else {
        this.getProvince();
      }
    },
    getProvince() {
      let data = {
        area_id: this.addressId,
      };
      areaList(data)
        .then((res) => {
          let code = res.data.code;
          if (code == 200) {
            this.addressColumn1 = res.data.datas.area_list;
            this.addressColumn1.unshift({
              area_id: 0,
              area_name: "请选择",
            });
            this.makeData();
          }
        })
        .catch((error) => {});
    },
    getCity() {
      let data = {
        area_id: this.addressId,
      };
      areaList(data)
        .then((res) => {
          let code = res.data.code;
          if (code == 200) {
            this.addressColumn2 = res.data.datas.area_list;
          }
        })
        .catch((error) => {});
    },
    getArea() {
      let data = {
        area_id: this.addressId,
      };
      areaList(data)
        .then((res) => {
          let code = res.data.code;
          if (code == 200) {
            this.addressColumn3 = res.data.datas.area_list;
          }
        })
        .catch((error) => {});
    },
    onBridgeReady(config) {
      WeixinJSBridge.invoke(
        "getBrandWCPayRequest",
        {
          appId: config.appId, //公众号名称，由商户传入
          timeStamp: config.timeStamp, //时间戳，自1970年以来的秒数
          nonceStr: config.nonceStr, //随机串
          package: config.package,
          signType: config.signType, //微信签名方式：
          paySign: config.paySign, //微信签名
        },
        (res) => {
          if (res.err_msg == "get_brand_wcpay_request:ok") {
            // 支付成功
            this.$router.push({
              name: "pay-notify",
              query: {
                pay: 1,
              },
            });
          } else {
            //支付失败
            this.$router.push({
              name: "pay-notify",
              query: {
                pay: 0,
              },
            });
          }
        }
      ).catch((error) => {});
    },
    goInvoice() {
      this.setLocalStorage();
      this.$router.push({
        name: "invoice-information",
      });
    },
    setLocalStorage() {
      let data = {
        key: this.key,
        area_id: this.areaId,
        city_id: this.cityId,
        sampling_time: this.samplingTime,
        area_info: this.areaInfo,
        address: this.address,
        soil_id: this.soilId,
        texture_id: this.textureId,
        soil_name: this.soilName,
        texture_name: this.textureName,
        plant_area: this.plantArea,
        previous_crop: this.previousCrop,
        output: this.output,
        season_crop: this.seasonCrop,
        target_output: this.targetOutput,
        phone: this.phone,
        name: this.name,
        purpose: this.purpose,
        invoice_id: this.invoiceId,
        proof_path: this.proofPath,
        sample_number: this.sampleNumber,
        latitude: this.latitude,
        longitude: this.longitude,
        payment_amount_type: this.paymentAmountType
      };
      localStorage.setItem("testingInfo", JSON.stringify(data));
    },
    goContract() {
      this.setLocalStorage();
      this.$router.push({
        name: "disclaimer",
      });
    },
  },
  filters: {},
};
</script>
<style scoped>
.purchase-information {
  width: 100%;
  background: #fff;
}
.purchase-information-bottom {
  background: #fff;
  padding: 30px 25px 40px;
  box-sizing: border-box;
}
.weixin-img {
  display: flex;
  align-items: center;
  margin-bottom: 10px;
}
.weixin-img1 {
  width: 16px;
  height: 16px;
  margin-right: 12px;
}
.weixin-img2 {
  width: 40px;
  height: 40px;
  margin-right: 15px;
}
.weixin-img span {
  font-size: 15px;
  color: #666;
}
.purchase-information-btn {
  width: 100%;
  height: 40px;
  text-align: center;
  line-height: 40px;
  background: #39a794;
  margin: 0 auto;
  display: block;
  color: #fff;
  border-radius: 30px;
  border: 0;
}
.contract {
  font-size: 14px;
  height: 16px;
  line-height: 16px;
  margin-bottom: 40px;
}
.contract >>> .van-checkbox {
  display: inline;
}
.contract span {
  color: #15c182;
}
.contract >>> .van-checkbox__icon .van-icon {
  width: 16px;
  height: 16px;
  font-size: 12px;
  line-height: 16px;
}
.contract >>> .van-checkbox__icon {
  height: 16px;
}
.purchase-information-btn.no-submit {
  background: rgba(57, 167, 148, 0.5);
}
</style>